package com.qs.eggs.view.prodetail.fragment;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.qs.eggs.Constants;
import com.qs.eggs.R;
import com.qs.eggs.account.LoginActivity;
import com.qs.eggs.adapter.ProAdapter;
import com.qs.eggs.api.HttpApi;
import com.qs.eggs.base.fragment.BaseFragment;
import com.qs.eggs.refresh.utils.TDevice;
import com.qs.eggs.utils.SpacesItemDecoration;
import com.qs.eggs.view.activity.SubmitOrderActivity;
import com.qs.eggs.view.prodetail.activity.ProDetailActivity;
import com.qs.eggs.widgets.count.SnappingStepper;
import com.qs.eggs.widgets.count.SnappingStepperValueChangeListener;

import com.qs.eggs.widgets.custom.MyScrollView;
import com.qs.eggs.widgets.custom.NetworkImageHolderView;

import com.qs.eggs.widgets.custom.PullToRefreshView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static com.qs.eggs.R.id.convenientBanner;

/**
 * A simple {@link Fragment} subclass.
 */
public  class ProductFragment extends BaseFragment implements View.OnClickListener,PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener{
    private PullToRefreshView mPullToRefreshView;
    private TextView name,kuaidi,price,yuexiao,address,canshu,num,logo,user,date,comment,tv_shoucang;
    private RelativeLayout shoucang;
    private  String proid,type;
    private ConvenientBanner slider;
    private  String jiage,xiaoliang;
    private RatingBar star;
    private String scores,custname,createtime,pinglun;
    private Button all;
    private RecyclerView gridView;
    private ProAdapter proAdapter;
    private ImageView cang;

    private String proname,priceS,specification;
    private TextView addCart,toPay;
    private SnappingStepper snappingStepper;
    private String count;
    int bwidth = 650;
    int bHeight = 650;
    private MyScrollView scrollView;
    private LinearLayout ll_pingjia;

    private String mCount="1";

    private List<Map<String, Object>>mlist = null;
    private String id;
    private List<String> networkImages;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_product;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        proid=getActivity().getIntent().getStringExtra("proid");
        type=getActivity().getIntent().getStringExtra("type");
        mPullToRefreshView =findView(R.id.main_pull_refresh_view);
        slider=findView(convenientBanner);
        name=findView(R.id.name);
        shoucang=findView(R.id.rl_shoucang);
        cang=findView(R.id.shoucang);
        tv_shoucang=findView(R.id.tv_shoucang);
        price=findView(R.id.jiage);
        yuexiao=findView(R.id.yuexiao);
        canshu=findView(R.id.canshu);
        num=findView(R.id.num);
        logo=findView(R.id.logo);
        user=findView(R.id.tv_comment_user);
        date=findView(R.id.tv_comment_date);
        comment=findView(R.id.tv_comment);
        star=findView(R.id.room_ratingbar);
        all=findView(R.id.all);
        addCart=findView(R.id.tv_add_cart);
        snappingStepper=findView(R.id.step_count);
        snappingStepper.setValue(1);
        snappingStepper.setMinValue(1);
        toPay=findView(R.id.tv_topay);
        gridView=findView(R.id.recyclerview);
        ll_pingjia=findView(R.id.ll_pingjia);
        scrollView=findView(R.id.scrollView);
        shoucang.setOnClickListener(this);
        canshu.setOnClickListener(this);
        addCart.setOnClickListener(this);
        toPay.setOnClickListener(this);
        all.setOnClickListener(this);
        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);
        count="1";
        snappingStepper.setOnValueChangeListener(new SnappingStepperValueChangeListener() {
            @Override
            public void onValueChange(View view, int value) {
                count=value+"";
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        gridView.setLayoutManager(linearLayoutManager);

        ifLogin1();

    }
    @Override
    protected void initData() {
        super.initData();
        initImageLoader();
        getPic();

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_shoucang:
                ifLogin();
                break;
            case R.id.canshu:
                ViewPager viewPager=(ViewPager) ProDetailActivity.instance.findViewById(R.id.guide_viewPager);
                viewPager.setCurrentItem(1);
                break;
            case R.id.tv_add_cart:
                HttpApi.cheakIsLogin(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s.equals("\"true\"")){
                            addCart();
                        }else {
                            LoginActivity.show(getContext());
                        }
                    }
                });

                break;
            case R.id.tv_topay:
                HttpApi.cheakIsLogin(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s.equals("\"true\"")){
                            Intent intent=new Intent(getContext(), SubmitOrderActivity.class);
                            intent.putExtra("proid",proid);
                            intent.putExtra("type",type);
                            intent.putExtra("totalcount",count);
                            intent.putExtra("iscart","false");
                            intent.putExtra("id",id);
                            startActivity(intent);
                        }else {
                            LoginActivity.show(getContext());
                        }
                    }
                });

                break;
            case R.id.all:
                ViewPager viewPager1=(ViewPager) ProDetailActivity.instance.findViewById(R.id.guide_viewPager);
                viewPager1.setCurrentItem(2);
                break;

        }
    }
    //加入购物车
    private void addCart(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid",proid);
        map.put("proname",proname);
        map.put("price",priceS);
        map.put("count",count);
        map.put("type",type);
        map.put("specification",specification);
        Gson gson=new Gson();
        String str=gson.toJson(map);
        OkGo.post(Constants.URL_BASE+"shoppingcart?action=addShoppingCart")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s.equals("\"true\"")){
                            Toast.makeText(getContext(),"加入购物车成功",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(getContext(),"加入购物车失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }
    //初始化网络图片缓存库
    private void initImageLoader(){
        //网络图片例子,结合常用的图片缓存库UIL,你可以根据自己需求自己换其他网络图片库
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().
                showImageForEmptyUri(R.mipmap.ic_default_adimage)
                .cacheInMemory(true).cacheOnDisk(true).build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getActivity().getApplicationContext()).defaultDisplayImageOptions(defaultOptions)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }
    //获得商品详情图片
    private  void getPic() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("proid", proid);
        map.put("type", type);
        Gson gson = new Gson();
        String str = gson.toJson(map);

        OkGo.post(Constants.URL_BASE + "mall/showproduct?action=productPicDetail")
                .params("data", str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONArray jsonArray = new JSONArray(s);
                            String[] images=new String[jsonArray.length()];
                            for (int i = 0; i < jsonArray.length(); i++) {
                                //准备好要显示的数据
                                images[i]=Constants.URL_BASE + jsonArray.getJSONObject(i).getString("folder") + jsonArray.getJSONObject(i).getString("autoname")+"";

                                networkImages=Arrays.asList(images);
                                    int width =(int)TDevice.getScreenWidth();
                                    int height = width * bHeight / bwidth;
                                    ViewGroup.LayoutParams para = slider.getLayoutParams();
                                    para.height = height;
                                    slider.setLayoutParams(para);
                                  slider.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
                                    @Override
                                    public NetworkImageHolderView createHolder() {
                                        return new NetworkImageHolderView();
                                    }
                                },networkImages);
                                }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        getProDetail();
                        getCount();
                        getPingjia();

                    }
                });

    }



    /**
     * 获取商品信息
     */
    private void getProDetail(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid",proid);
        map.put("type",type);
        Gson gson=new Gson();
        String str=gson.toJson(map);
        OkGo.post(Constants.URL_BASE+"mall/showproduct?action=productDetail")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("商品信息=="+s);
                        try {
                            JSONArray jsonArray = new JSONArray(s);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                id=jsonArray.getJSONObject(i).getString("proid");
                                jiage=jsonArray.getJSONObject(i).getString("proprice");
                                specification=jsonArray.getJSONObject(i).getString("specification");
                                priceS=jsonArray.getJSONObject(i).getString("proprice");
                                proname=jsonArray.getJSONObject(i).getString("proname");
                                price.setText("¥"+jiage+"");
                                name.setText(proname);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    //获得商品销量
    private void getCount(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid",proid);
        map.put("type",type);
        Gson gson=new Gson();
        String str=gson.toJson(map);
        OkGo.post(Constants.URL_BASE+"mall/showproduct?action=getTotalMonthCount")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONArray jsonArray = new JSONArray(s);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                xiaoliang=jsonArray.getJSONObject(i).getString("count");
                                yuexiao.setText("月销"+xiaoliang+"");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    //获得商品评价
    private void getPingjia(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid",proid);
        map.put("type",type);
        Gson gson=new Gson();
        String str=gson.toJson(map);
        OkGo.post(Constants.URL_BASE+"evaulteManage?action=searchEvalute")
                .params("params",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        getProduct();
                        System.out.print("评价=="+s);
                        if (s.equals("\"false\"")){
                            ll_pingjia.setVisibility(View.GONE);
                        }else {
                            try {
                                JSONArray jsonArray = new JSONArray(s);
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    scores = jsonArray.getJSONObject(0).getString("scores");
                                    custname = jsonArray.getJSONObject(0).getString("custname");
                                    pinglun = jsonArray.getJSONObject(0).getString("comments");
                                    createtime = jsonArray.getJSONObject(0).getString("createtime");
                                    comment.setText(pinglun);
                                    logo.setText("V" + scores + "");
                                    user.setText(custname);
                                    date.setText(createtime);
                                    star.setRating(Float.valueOf(scores));
                                    num.setText("商品评价" + "(" + jsonArray.length() + ")");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            getProduct();
                        }
                    }
                });

    }
    //大家都在看
    private void getProduct(){
        OkGo.post(Constants.URL_BASE+"mall/showproduct?action=getOrderProduct")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("都在看=="+s);
                        try {
                            mlist=new ArrayList<>();
                            JSONArray jsonArray = new JSONArray(s);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject  jsonObject=jsonArray.getJSONObject(i);
                                Map<String,Object> map=new HashMap<>();
                                map.put("proid",jsonObject.getString("proid"));
                                map.put("price",jsonObject.getString("price"));
                                map.put("type",jsonObject.getString("type"));
                                map.put("proname",jsonObject.getString("proname"));
                                map.put("autoname",jsonObject.getString("autoname"));
                                map.put("count",jsonObject.getString("count"));
                                mlist.add(map);
                            }
                            proAdapter = new ProAdapter(getActivity(), mlist);
                            gridView.setAdapter(proAdapter);
                            gridView.addItemDecoration(new SpacesItemDecoration(20));
                            proAdapter.notifyDataSetChanged();
                            proAdapter.setOnItemClickListener(new ProAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    ProDetailActivity.instance.finish();
                                    Intent intent=new Intent(getActivity(),ProDetailActivity.class);
                                    intent.putExtra("proid",mlist.get(position).get("proid").toString());
                                    intent.putExtra("type",mlist.get(position).get("type").toString());
                                    startActivity(intent);
                                }
                            });

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }
    //添加浏览历史
    private void getLookHistory(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid",proid);
        map.put("type",type);
        Gson gson=new Gson();
        String str=gson.toJson(map);
        OkGo.post(Constants.URL_BASE+"lookhistory?action=insertLookHistory")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                    }
                });

    }
    //添加收藏
    private void collect(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid",proid);
        map.put("type",type);
        Gson gson=new Gson();
        String str=gson.toJson(map);
        OkGo.post(Constants.URL_BASE+"collect?action=addCollection")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("收藏=="+s);
                        if (s.equals("\"true\"")){
                            cang.setImageResource(R.mipmap.star2);
                            tv_shoucang.setText("已收藏");
                        }else {

                        }
                    }
                });
    }
    //检查是否添加收藏
    private void checkCollection(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid",proid);
        map.put("type",type);
        Gson gson=new Gson();
        String str=gson.toJson(map);
        OkGo.post(Constants.URL_BASE+"collect?action=checkCollection")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("是否收藏=="+s);
                        if (s.equals("\"true\"")){
                            cang.setImageResource(R.mipmap.star2);
                            tv_shoucang.setText("已收藏");
                            shoucang.setClickable(false);
                        }else{
                            cang.setImageResource(R.mipmap.star1);
                            tv_shoucang.setText("收藏");
                        }
                    }
                });
    }
    //监测是否登录
    private void ifLogin(){
        OkGo.post(Constants.URL_BASE+"mallLogin?action=isLogin")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if(s.equals("\"false\"")){
                            LoginActivity.show(getContext());
                        }else {
                            collect();
                        }
                    }
                });

    }
    //判断是否登录
    private void ifLogin1(){
        HttpApi.cheakIsLogin(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if(s.equals("\"false\"")){
                    cang.setImageResource(R.mipmap.star1);
                    tv_shoucang.setText("收藏");
                }else {
                    checkCollection();
                    getLookHistory();

                }
            }
        });

    }
    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                handler.sendEmptyMessage(1);
                ViewPager viewPager=(ViewPager) ProDetailActivity.instance.findViewById(R.id.guide_viewPager);
                viewPager.setCurrentItem(1);
                mPullToRefreshView.onFooterRefreshComplete();
            }
        }, 1000);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                handler.sendEmptyMessage(1);
                getPic();
                getProDetail();
                getCount();
                getPingjia();
                getProduct();
                mPullToRefreshView.onHeaderRefreshComplete();
            }
        }, 1000);

    }
	/*-----------刷新接口方法实现-------	*/

    Handler handler = new Handler() {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            mPullToRefreshView.onFooterRefreshComplete();

        }

    };
    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        slider.startTurning(3000);
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        slider.stopTurning();
    }


}
